/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.app.client.form.bindings;

import org.nuxeo.gwt.habyt.app.client.form.FormControl;
import org.nuxeo.gwt.habyt.app.client.form.layout.ControlRow;
import org.nuxeo.gwt.habyt.app.client.form.validators.AndValidator;
import org.nuxeo.gwt.habyt.app.client.form.validators.RequiredValidator;
import org.nuxeo.gwt.habyt.app.client.form.validators.Validators;
import org.nuxeo.gwt.habyt.templates.client.Constants;
import org.nuxeo.gwt.habyt.templates.client.WidgetFactory;
import org.nuxeo.gwt.habyt.templates.client.bindings.BuiltinWidgets.BCheckBox;
import org.nuxeo.gwt.habyt.templates.client.bindings.BuiltinWidgets.BRadioButton;
import org.nuxeo.gwt.habyt.templates.client.bindings.Helper;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public abstract class AbstractControlFactory extends WidgetFactory {

    public AbstractControlFactory(String id) {
        super(id);
    }

    protected abstract FormControl createControl(Element element);

    @Override
    protected Widget createWidget(Element element) {
        FormControl control = createControl(element);
        String v = Helper.getAttribute(element, Constants.VALIDATE_REQUIRED);
        AndValidator validator = new AndValidator();
        control.setValidator(validator);
        if (v != null && "true".equalsIgnoreCase(v)) {
            validator.add(new RequiredValidator());
        }
        v = Helper.getAttribute(element, Constants.VALIDATE_FUNCTION);
        if (v != null) {
            validator.add(Validators.newValidator(v));
        }
        v = Helper.getAttribute(element, Constants.VALIDATE_ERROR);
        if (v != null) {
            control.setErrorMessage(v);
        }
        v = Helper.getAttribute(element, Constants.LABEL);
        if (v != null) {
            control.setLabel(v);
            Widget w = control.getWidget();
            if (w instanceof BCheckBox || w instanceof BRadioButton) {
                return new ControlRow(control, false);
            } else {
                return new ControlRow(control);
            }
        }

        return control;
    }

}
